// pages/orderDetail/index.js

const service = require("../../../service/port.js");
import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
const uploadImage = require("../../../utils/uploadImg/uploadImg.js");
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast.js";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    bool: false,
    orderinfo: {
      receiver: "李建民",
      receiverMobile: "15144556231",
      receiverAddress: "吉林省长春市高薪区硅谷大街501号硅谷大厦309室（万豪对面）",
      price: 10,
      num: 2,
      ownSpec: "净含量：6ml",
      totalPay: 20,
      postFee: "免邮费",
      damondNum: 2,
      buyerMessage: "赠送小样",
      actualPay: 8,
      orderNum: "22001220325636",
      createTime: "2020-06-12 21:21:03",
      paymentTime: "2020-06-12 21:21:03",
      receivTime: "2020-06-12 21:21:03",
    },
    returnReson: "",
    showrefundsbtn: false,
    showrefundsbtn1: false,
    status: 1,
    show: false,
    radio: 1,
    showrefunds: false,
    showrefunds1: false,
    cash: 0,
    fileList: [],
    refundsprogress: false,
    reson: "",
    refundMoney: 200,
    fileList1: [],
    array: ["已收货", "未收货"],
    time: 0,
    otherReason: "",
    refundprogressShow: false,
    resons: "", //退款进度 退款原因
    images: [], //退款进度 品正图片
    returnMoney: "",
    currentOrder: "",
    returnCreateTime: "",
    appStu: 0, //审批状态 0待审批 1 同意 2拒绝
    appResult: "",
    returnModifyTime: "",
    totalnum: 0,
    singelproduct: {},
    postFee: 0,
    refundAmount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.log(options);
    service.orderDetail(options.id, (res) => {
      console.log(res);

      res.data.freightMoney1 = res.data.freightMoney == 0 ? "免邮费" : '￥' + res.data.freightMoney / 100;
      let totalnum = 0;
      res.data.orderdetailList.forEach(item => {
        totalnum += item.num
      })
      this.setData({
        orderinfo: res.data,
        totalnum: totalnum,
      });
      //console.log(111111,res,res.data)
      if (res.data.status == 1) {
        var now = new Date().getTime();
        var closetime = new Date(res.data.createTime.replace(/-/g, '/')).getTime() + 15 * 60 * 1000;
        if (closetime > now) {
          this.setData({
            time: closetime - now,
          });

        }
      }
    });
  },
  togglebtn: function () {
    var value = !this.data.showrefundsbtn;
    this.setData({
      showrefundsbtn: value
    })

  },
  cancelOrder: function () {
    this.setData({
      show: true,
    });
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  onClose: function () {
    this.setData({
      show: false,
    });
  },
  blurEvent: function (e) {
    this.setData({
      otherReason: e.detail.value,
    });
  },
  onClick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      radio: name,
    });
  },
  checkLogistics: function () {
    wx.navigateTo({
      url: "/pages/order/logistics/index?id=" + this.data.orderinfo.orderNum,
    });
  },
  //退款原因
  getreturnReson: function (e) {
    this.setData({
      returnReson: e.detail.value,
    });
  },
  afterRead: function (e) {
    console.log(e);
    var list = this.data.fileList;
    list.push({
      url: e.detail.file.path,
    });
    this.setData({
      fileList: list,
    });
  },
  deletephoto: function (event) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList,
    });
  },
  applyRefund: function () {
    this.setData({
      showrefunds: true,
    });
    if (this.data.orderinfo.status == "2") {
      this.setData({
        refundAmount: this.data.orderinfo.actualPrice
      })
    } else {
      this.setData({
        refundAmount: this.data.orderinfo.actualPrice - this.data.orderinfo.freightMoney / 100
      })
    }
  },
  applyRefund1: function (e) {
    //console.log(e)
    this.setData({
      showrefunds1: true,
      singelproduct: (e.currentTarget.dataset.index.num * e.currentTarget.dataset.index.productPrice).toFixed(2),
      refundAmount: (e.currentTarget.dataset.index.num * e.currentTarget.dataset.index.productPrice).toFixed(2)
    });

  },
  onClose1: function () {
    // setTimeout(function(){
    this.setData({
      showrefunds: false,
      showrefunds1: false,
    });
    // },500)

  },
  //退款进度
  progressClose: function (e) {
    this.setData({
      refundprogressShow: false,
    });
  },
  progressShow: function (e) {
    console.log(e);
    let imagedata = e.currentTarget.dataset.index.images.split(",");
    this.setData({
      refundprogressShow: true,
      resons: e.currentTarget.dataset.index.returnReson,
      returnMoney: e.currentTarget.dataset.index.returnPrice,
      images: imagedata,
      returnCreateTime: e.currentTarget.dataset.index.returnCreateTime,
      appStu: e.currentTarget.dataset.index.appStu, //审批状态 0待审批 1 同意 2拒绝
      appResult: e.currentTarget.dataset.index.appResult,
      returnModifyTime: e.currentTarget.dataset.index.returnModifyTime,
    });
  },
  onClose2: function () {

    // setTimeout(function(){
    this.setData({
      refundsprogress: false,
    });
    // },500)
  },
  onChange1: function (event) {
    console.log(event);
  },
  bindPickerChange: function (e) {
    console.log("picker发送选择改变，携带值为", e.detail.value);
    this.setData({
      index: e.detail.value,
    });
  },
  gocomment(e) {
    //console.log(e);
    wx.navigateTo({
      url: '/pages/evaluate/index?spuId=' + e.currentTarget.dataset.index.spuId + "&orderDetAllId=" + e.currentTarget.dataset.index.id,
    })
  },
  //确定退款
  confirmRefund: function () {
    // for (var i = 0; i < this.data.fileList.length; i++) {
    //   //显示消息提示框

    //   //上传图片
    //   //你的域名下的/images/当前年月日文件下的/图片.png
    //   //图片路径可自行修改【(这二个参数就是你oss地址目录的下一个路径目录，比如:https://xxx.com/images/xxx.png)】
    //   uploadImage(this.data.fileList[i].url, 'images/',
    //     function (result) {
    //       console.log("======上传成功图片地址为：", result);
    //       //这个result就是返给你上传到oss上的地址链接
    //       wx.hideLoading();
    //     }, function (result) {
    //       console.log("======上传失败======", result);

    //       wx.hideLoading()
    //     }
    //   )
    // }
    var self = this;
    wx.showLoading({
      title: "正在上传图片",
      mask: true,
    });
    var imglist = [];

    function uploadimg() {
      if (self.data.fileList.length > 0) {
        var imgpath = self.data.fileList.pop();
        uploadImage(
          imgpath.url,
          "images/",
          function (result) {
            console.log("======上传成功图片地址为：", result);
            imglist.push(result);
            //这个result就是返给你上传到oss上的地址链接
            uploadimg();
          },
          function (result) {
            console.log("======上传失败======", result);
            Toast.fail("上传失败");
            // wx.hideLoading();
            uploadimg();
          }
        );
      } else {
        service.applyRefund({
          orderId: self.data.orderinfo.id, //订单标识
          returnReson: self.data.returnReson, //退货原因
          images: imglist.toString(), //凭证图片
          appcustomerId: wx.getStorageSync("userInfo").id, //审批人标识
          "orderDetailId": "",
          "type": "0", //退款类型 0订单退款 1 单商品退款
          "orderStatus": self.data.orderinfo.status,
          "refundAmount": self.data.refundAmount * 100
        },
          (res) => {
            console.log(res);
            wx.hideLoading();
            if (res.code == "B0001") {
              Toast.fail(res.message);
              return
            }
            Toast.success("申请成功");
            self.setData({
              showrefunds: false,
              showrefunds1: false,
            });

          }
        );
      }
    }
    uploadimg();
  },
  //确定退款2
  confirmRefund2: function () {

    var self = this;
    wx.showLoading({
      title: "正在上传图片",
      mask: true,
    });
    var imglist = [];

    function uploadimg() {
      if (self.data.fileList.length > 0) {
        var imgpath = self.data.fileList.pop();
        uploadImage(
          imgpath.url,
          "images/",
          function (result) {
            console.log("======上传成功图片地址为：", result);
            imglist.push(result);
            //这个result就是返给你上传到oss上的地址链接
            uploadimg();
          },
          function (result) {
            console.log("======上传失败======", result);
            Toast.fail("上传失败");
            // wx.hideLoading();
            uploadimg();
          }
        );
      } else {
        service.applyRefund({
          orderId: self.data.orderinfo.id, //订单标识
          returnReson: self.data.returnReson, //退货原因
          images: imglist.toString(), //凭证图片
          appcustomerId: wx.getStorageSync("userInfo").id, //审批人标识
          "orderDetailId": self.data.showrefundsbtn1,
          "type": "1", //退款类型 0订单退款 1 单商品退款
          "orderStatus": self.data.orderinfo.status,
          "refundAmount": self.data.refundAmount * 100
        },
          (res) => {
            console.log(res);
            wx.hideLoading();
            if (res.code == "B0001") {
              Toast.fail(res.message);
              return
            }
            Toast.success("申请成功");
            self.setData({
              showrefunds: false,
              showrefunds1: false,
            });

          }
        );
      }
    }
    uploadimg();
  },
  //确认收货
  receiving: function () {
    Dialog.confirm({
      title: "提示",
      message: "确认收货吗？",
    })
      .then(() => {
        // on confirm
        const self = this;
        service.confirmReceipt({
          orderId: this.data.orderinfo.id, //订单标识
        },
          function (res) {
            wx.showToast({
              title: "收货成功",
              icon: "success",
              duration: 2000,
            });
          }
        );
      })
      .catch(() => {
        // on cancel
      });
  },
  //取消订单
  confirmCancel: function () {
    const self = this;
    service.cancleTbOrder({
      orderId: this.data.orderinfo.id, //订单标识
      status: "5", //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败
      reason: this.data.radio, //取消原因
      other: this.data.otherReason, //其他原因
    },
      function (res) {
        wx.showToast({
          title: "取消成功",
          icon: "success",
          duration: 2000,
        });
        self.setData({
          show: false,
        });
        wx.navigateBack({
          delta: 1,
        });
      }
    );
  },
  //立即支付
  payNow: function () {
    service.payment({
      id : this.data.orderinfo.id,
      orderNum: this.data.orderinfo.orderNum, //订单编号
      actualPay: this.data.orderinfo.actualPay, //res.data.actualPay//实付金额。单位:分。如:20007，表示:200元7分
      title: this.data.orderinfo.orderdetailList.length > 1 ? "商品描述" : this.data.orderinfo.orderdetailList[0].title,
      customerId: wx.getStorageSync("userInfo").id,
      openid: wx.getStorageSync("userInfo").openId,
    },
      (res1) => {
        if (res1.code == 'B0001') {
          wx.showToast({
            title: '呀,出错了!',
          })
          return
        }
        wx.requestPayment({
          appId: res1.data.appId,
          timeStamp: res1.data.timeStamp,
          nonceStr: res1.data.nonceStr,
          package: res1.data.package,
          signType: res1.data.signType,
          paySign: res1.data.sign,

          success(res) {
            Toast.success("支付成功");
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              })
            }, 2000)

          },
          fail(res) {
            console.log(res);
            Toast.fail("支付失败");
          },
        });
      }
    );
  },
  //删除订单
  deleteOrder: function () {
    Dialog.confirm({
      title: "提示",
      message: "确认删除该订单吗？",
    })
      .then(() => {
        // on confirm
        const self = this;
        service.cancleTbOrder({
          orderId: this.data.orderinfo.id, //订单标识
          status: "10", //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败 10 删除订单
        },
          function (res) {
            wx.showToast({
              title: "删除成功",
              icon: "success",
              duration: 2000,
            });
          }
        );
      })
      .catch(() => {
        // on cancel
      });
  },
  togglebtn1: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.index.id
    if (this.data.showrefundsbtn1 == index) {
      this.setData({
        showrefundsbtn1: false
      })
    } else {
      this.setData({
        showrefundsbtn1: index
      })
    }
  },
  previewImg: function (e) {
    console.log(e);
    var imgUrls = e.currentTarget.dataset.item;
    //图片预览
    wx.previewImage({
      current: imgUrls, // 当前显示图片的http链接
      urls: this.data.images
    })
  },
  finished() {
    wx.navigateTo({
      url: '/pages/mine/order/closerList/index',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
});